package com.halflife.framework.generator.template.mapper;

import com.halflife.framework.generator.GenerateUtil;
import com.halflife.framework.generator.annotation.QueryAnn;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;

/**
 * Created by zhaoyf on 2018/6/18.
 */
public class ReferResultMapAnalysis extends BaseAnalysis {
    public ReferResultMapAnalysis(Class clazz) {
        super(clazz);
    }


    protected void setPrefix() {
        this.xmlStr.append( "<resultMap id=\"referedResultMap\" type=\"" + this.clazz.getName() + "\">\n");

    }
    protected void fieldAnaysis1() {
        final int[] len = {0};
        for (Field field : fields) {
            QueryAnn ann = field.getAnnotation(QueryAnn.class);
            if (ann==null||!ann.refered()) {
                continue;
            }
            //默认引用对象都会被引入
            if (field.getType().getPackage().getName().indexOf("com.halflife") > -1){
                xmlStr.append("\t<association property=\""+field.getName()+"\"");
                xmlStr.append(" columnPrefix=\""+field.getType().getSimpleName()+"_\"");
                xmlStr.append(" resultMap=\""+field.getType().getName()+"Repository.referedResultMap"+"\" />");
            }else{
                if (ann==null||!ann.refered()) {
                    continue;
                }
                CustomField customField = new CustomField(field);
                try {
                    String str = this.getValue1(customField);
                    xmlStr.append("\t");
                    xmlStr.append(str);
                    len[0] += str.length();
                } catch (RuntimeException e) {
                    continue;
                }
            }

            //value==null 说明是特殊字段


            xmlStr.append(this.getLineSuffix(len));
        }
    }
    @Override
    protected String getValue1(CustomField customField) {
        if (!customField.isPersist()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        if (customField.getName().equals("id")) {
            sb.append("<id column=\"").append(customField.getName()).append("\" jdbcType=\"").append(customField.getTypeName().toUpperCase()).append("\" property=\"").append(customField.getName()).append("\"/>");
        } else
            sb.append("<result column=\"").append(customField.getName()).append("\" jdbcType=\"").append(customField.getTypeName().toUpperCase()).append("\" property=\"").append(customField.getName()).append("\"/>");
        return sb.toString();
    }

    protected String getLineSuffix(int[] len) {
        return "\n";
    }

    ;

    protected void setSuffix() {

        this.xmlStr.append( " </resultMap>");
    }

    ;
}
